<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="referrer" content="no-referrer" />
    <title>视频播放页面</title>
    <link rel="stylesheet" href="/css/video.css" />
    <script src="/js/jquery-1.9.1.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="nav-tabs">
        <!-- 导航标签将由JavaScript动态生成 -->
      </div>

      <div class="content-box">
        <div class="video-list">
          <div class="content-tabs">
            <!-- <div class="tab-header">
              <div class="tab-header-item" data-tab="video">视频</div>
              <div class="tab-header-item" data-tab="text">文案</div>
              <div class="tab-header-item" data-tab="cover">封面</div>
            </div> -->

            <div class="tab-content video-container" id="video-tab">
              <video
                src=""
                controls
                autoplay
                style="width: 100%; height: 100%"
              ></video>
            </div>

            <!-- <div class="tab-content" id="text-tab">
              <div class="text-content" style="color: white; padding: 20px">
                <p>这里是文案内容</p>
              </div>
            </div>
            <div class="tab-content" id="cover-tab">
              <div
                class="cover-content"
                style="color: white; padding: 20px; text-align: center"
              >
                <img style="width: 300px; height: 300px" alt="" />
              </div>
            </div> -->
          </div>
          <h1 class="product-title text-content1"></h1>
          <div class="action-buttons">
            <button class="btn btn-outline">复制地址</button>
            <button class="btn btn-primary">下载视频</button>
            <button class="btn bottom-btn2">复制文案</button>
            <button class="btn bottom-btn1">保存音频</button>
            <!-- <button class="btn btn-home">返回首页</button> -->
          </div>
        </div>
        <div class="pic-list" style="display: none">
          <div class="image-grid content-tabs">
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节1" />
              <div class="check-icon"></div>
            </div>
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节2" />
              <div class="check-icon"></div>
            </div>
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节3" />
              <div class="check-icon"></div>
            </div>
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节4" />
              <div class="check-icon"></div>
            </div>
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节5" />
              <div class="gray-dot"></div>
            </div>
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节6" />
              <div class="gray-dot"></div>
            </div>
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节7" />
              <div class="gray-dot"></div>
            </div>
            <div class="image-item">
              <img src="/static/icon7.png" alt="商品细节8" />
              <div class="gray-dot"></div>
            </div>
          </div>
          <h1 class="product-title text-content2">
            双面摇粒绒外套女春秋冬季2025新款羊羔毛加厚内胆飘粒绒内搭卫衣
          </h1>
          <div class="action-buttons">
            <button class="btn btn-outline piliang">批量下载</button>
            <button class="btn btn-primary downall">一键下载</button>
            <button class="btn bottom-btn3">复制文案</button>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
<script>
  const resources = JSON.parse(sessionStorage.getItem("resources"));
  console.log("解析资源", resources);

  // 动态生成导航标签
  const navTabs = document.querySelector(".nav-tabs");
  if (resources && resources.length > 0) {
    resources.forEach((_, index) => {
      const tab = document.createElement("button");
      tab.className = `nav-tab ${index === 0 ? "active" : ""}`;
      tab.setAttribute("data-index", index);
      tab.textContent = `链接${index + 1}`;
      navTabs.appendChild(tab);
    });
  }

  // 设置视频源
  const videoElement = document.querySelector("video");
  const textElement1 = document.querySelector(".text-content1");
  const textElement2 = document.querySelector(".text-content2");
  //   const imgElement = document.querySelector(".cover-content img");

  // 更新资源显示
  function updateResource(index) {
    if (resources && resources.length > 0 && resources[index]) {
      const { data } = resources[index];
      const isVideo = data.res.filter((item) => item.resType == "3");
      const isAudio = data.res.filter((item) => item.resType == "2");
      textElement1.textContent = data.desc || data.title;
      textElement2.textContent = data.desc || data.title;
      //   imgElement.src = data.pic;
      if (isAudio.length > 0) {
        $(".bottom-btn1").show();
      } else {
        $(".bottom-btn1").hide();
      }
      if (isVideo.length > 0) {
        videoElement.src = data.res[0].resUrl;
        $(".video-list").show();
        $(".pic-list").hide();
      } else {
        // 动态创建图片网格
        createImageGrid(data.res);
        $(".video-list").hide();
        $(".pic-list").show();
      }
    }
  }

  // 动态创建图片网格
  function createImageGrid(resources) {
    const imageGrid = document.querySelector(".image-grid");
    imageGrid.innerHTML = ""; // 清空现有内容

    resources.forEach((item, index) => {
      if (item.resType == "1") {
        // 如果不是视频类型
        const imageItem = document.createElement("div");
        imageItem.className = "image-item";

        const img = document.createElement("img");
        img.src = item.resUrl;
        img.alt = `商品细节${index + 1}`;

        const checkIcon = document.createElement("div");
        checkIcon.className = "gray-dot";

        // 添加点击事件
        imageItem.addEventListener("click", () => {
          imageItem.classList.toggle("selected");
          if (imageItem.classList.contains("selected")) {
            checkIcon.className = "check-icon";
          } else {
            checkIcon.className = "gray-dot";
          }
        });

        imageItem.appendChild(img);
        imageItem.appendChild(checkIcon);
        imageGrid.appendChild(imageItem);
      }
    });
  }

  // 初始化显示第一个资源
  updateResource(0);

  // 为导航标签添加点击事件
  document.querySelectorAll(".nav-tab").forEach((tab) => {
    tab.addEventListener("click", () => {
      // 移除所有标签的激活状态
      document
        .querySelectorAll(".nav-tab")
        .forEach((t) => t.classList.remove("active"));
      // 添加当前标签的激活状态
      tab.classList.add("active");
      // 更新资源显示
      const index = parseInt(tab.getAttribute("data-index"));
      updateResource(index);
    });
  });

  // 复制视频地址功能
  document.querySelector(".btn-outline").addEventListener("click", async () => {
    try {
      const videoUrl = videoElement.src;
      await navigator.clipboard.writeText(videoUrl);
      alert("视频地址已复制到剪贴板");
    } catch (err) {
      console.error("复制失败:", err);
      alert("复制失败，请手动复制");
    }
  });

  // 保存视频功能
  document.querySelector(".btn-primary").addEventListener("click", async () => {
    try {
      let videoUrl = videoElement.src;
      // 将HTTPS转换为HTTP
      videoUrl = videoUrl.replace("http://", "https://");
      const response = await fetch(videoUrl);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      // 生成时间格式的文件名：YYYYMMDD_HHMMSS
      const now = new Date();
      const fileName = `${now.getFullYear()}${String(
        now.getMonth() + 1
      ).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(
        now.getHours()
      ).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(
        now.getSeconds()
      ).padStart(2, "0")}.mp4`;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err) {
      console.error("保存视频失败:", err);
      alert("保存视频失败，请重试");
    }
  });

  // 保存音频功能
  document.querySelector(".bottom-btn1").addEventListener("click", async () => {
    try {
      let videoUrl = videoElement.src;
      // 将HTTPS转换为HTTP
      videoUrl = videoUrl.replace("http://", "https://");
      const response = await fetch(videoUrl);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      // 生成时间格式的文件名：YYYYMMDD_HHMMSS
      const now = new Date();
      const fileName = `${now.getFullYear()}${String(
        now.getMonth() + 1
      ).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(
        now.getHours()
      ).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(
        now.getSeconds()
      ).padStart(2, "0")}.mp3`;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err) {
      console.error("保存音频失败:", err);
      alert("保存音频失败，请重试");
    }
  });

  // 复制文案功能
  document.querySelector(".bottom-btn2").addEventListener("click", async () => {
    try {
      const textContent = textElement1.textContent;
      await navigator.clipboard.writeText(textContent);
      alert("文案已复制到剪贴板");
    } catch (err) {
      console.error("复制文案失败:", err);
      alert("复制文案失败，请手动复制");
    }
  });
  // 复制文案功能
  document.querySelector(".bottom-btn3").addEventListener("click", async () => {
    try {
      const textContent = textElement2.textContent;
      await navigator.clipboard.writeText(textContent);
      alert("文案已复制到剪贴板");
    } catch (err) {
      console.error("复制文案失败:", err);
      alert("复制文案失败，请手动复制");
    }
  });

  // 返回首页功能
  //   document.querySelector(".btn-home").addEventListener("click", () => {
  //     window.location.href = "index.html";
  //   });

  // 批量下载图片功能
  document.querySelector(".piliang").addEventListener("click", async () => {
    try {
      const selectedImages = document.querySelectorAll(
        ".image-item .check-icon"
      );
      if (selectedImages.length === 0) {
        alert("请先选择要下载的图片！");
        return;
      }

      for (let i = 0; i < selectedImages.length; i++) {
        const imageItem = selectedImages[i].parentElement;
        const img = imageItem.querySelector("img");
        const response = await fetch(img.src);
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        // 生成时间格式的文件名：YYYYMMDD_HHMMSS_序号
        const now = new Date();
        const fileName = `${now.getFullYear()}${String(
          now.getMonth() + 1
        ).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(
          now.getHours()
        ).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(
          now.getSeconds()
        ).padStart(2, "0")}_${i + 1}.jpg`;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
      }
    } catch (err) {
      console.error("批量下载图片失败:", err);
      alert("批量下载图片失败，请重试");
    }
  });

  // 下载全部图片功能
  document.querySelector(".downall").addEventListener("click", async () => {
    try {
      const allImages = document.querySelectorAll(".image-item img");
      if (allImages.length === 0) {
        alert("没有可下载的图片！");
        return;
      }

      for (let i = 0; i < allImages.length; i++) {
        const img = allImages[i];
        const response = await fetch(img.src);
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        // 生成时间格式的文件名：YYYYMMDD_HHMMSS_序号
        const now = new Date();
        const fileName = `${now.getFullYear()}${String(
          now.getMonth() + 1
        ).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(
          now.getHours()
        ).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(
          now.getSeconds()
        ).padStart(2, "0")}_${i + 1}.jpg`;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
      }
    } catch (err) {
      console.error("下载全部图片失败:", err);
      alert("下载全部图片失败，请重试");
    }
  });

  //   // 获取所有标签页元素
  //   const tabItems = document.querySelectorAll(".tab-header-item");
  //   const tabContents = document.querySelectorAll(".tab-content");

  //   // 初始化第一个标签页为激活状态
  //   tabItems[0].classList.add("active");
  //   tabContents[0].classList.add("active");

  //   // 为每个标签页添加点击事件
  //   tabItems.forEach((item) => {
  //     item.addEventListener("click", () => {
  //       // 移除所有标签页的激活状态
  //       tabItems.forEach((tab) => tab.classList.remove("active"));
  //       tabContents.forEach((content) => content.classList.remove("active"));

  //       // 添加当前标签页的激活状态
  //       item.classList.add("active");
  //       const tabId = item.getAttribute("data-tab");
  //       document.getElementById(`${tabId}-tab`).classList.add("active");
  //     });
  //   });
</script>
